#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "App_Communication.h"
#include "App_Display.h"
#include "App_Key.h"
#include "App_Power.h"
#include "nvs_flash.h"

void KeyTaskFunc(void *args);
#define KEY_TASK_NAME "key_Task"
#define KEY_TASK_STACKDEPTH 4096
#define KEY_TASK_PRIORITY 4
TaskHandle_t Key_handle;

void PowerTaskFunc(void *args);
#define POWER_TASK_NAME "Power_Task"
#define POWER_TASK_STACKDEPTH 4096
#define POWER_TASK_PRIORITY 4
TaskHandle_t Power_handle;

void OLEDTaskFunc(void *args);
#define OLED_TASK_NAME "OLED_Task"
#define OLED_TASK_STACKDEPTH 4096
#define OLED_TASK_PRIORITY 3
TaskHandle_t OLED_handle;

void MQTTTaskFunc(void *args);
#define MQTT_TASK_NAME "MQTT_Task"
#define MQTT_TASK_STACKDEPTH 4096
#define MQTT_TASK_PRIORITY 3
TaskHandle_t MQTT_handle;

#include "App_Key.h"

void app_main(void) {
    MY_LOGE("hello");

    // 初始化NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // NVS出现错误，执行擦除
        ESP_ERROR_CHECK(nvs_flash_erase());
        // 重新尝试初始化
        ESP_ERROR_CHECK(nvs_flash_init());
    }

    Inf_Relay_Init();
    Inf_LED_Init();

    App_Key_Init();
    App_Power_Init();
    App_Display_Init();
    App_Communication_Init();

    // 按键任务-ADC检测
    xTaskCreate(KeyTaskFunc, KEY_TASK_NAME, KEY_TASK_STACKDEPTH, NULL, KEY_TASK_PRIORITY, &Key_handle);
    // 电量检测任务
    xTaskCreate(PowerTaskFunc, POWER_TASK_NAME, POWER_TASK_STACKDEPTH, NULL, POWER_TASK_PRIORITY, &Power_handle);
    // OLED显示任务
    xTaskCreate(OLEDTaskFunc, OLED_TASK_NAME, OLED_TASK_STACKDEPTH, NULL, OLED_TASK_PRIORITY, &OLED_handle);
    // MQTT发送任务
    xTaskCreate(MQTTTaskFunc, MQTT_TASK_NAME, MQTT_TASK_STACKDEPTH, NULL, MQTT_TASK_PRIORITY, &MQTT_handle);

    while (1) {
        vTaskDelay(100);
    }
}

void KeyTaskFunc(void *args) {
    MY_LOGE("按键任务开始调度。。。");

    while (1) {
        App_Key_Process();

        vTaskDelay(10);
    }
}

void PowerTaskFunc(void *args) {
    vTaskDelay(100);
    MY_LOGE("电量检测任务开始调度。。。");

    while (1) {
        App_Power_GetPower();

        vTaskDelay(10);
    }
}

void OLEDTaskFunc(void *args) {
    MY_LOGE("OLED显示任务开始调度。。。");

    while (1) {
        App_Display_Show();

        vTaskDelay(1000);
    }
}

void MQTTTaskFunc(void *args) {
    MY_LOGE("MQTT发送任务开始调度。。。");

    if (ulTaskNotifyTake(pdTRUE, portMAX_DELAY)) {
        Inf_MQTT_Init();

        while (1) {
            App_Communication_Transimit2MQTT();

            vTaskDelay(5000);
        }
    }

    while (1) {
        vTaskDelay(100);
    }
}
